import os

from flask import Flask, render_template, request, json

from transform_excel_tools.service.JsonResponse import JsonResponse
from transform_excel_tools.transform import TransformData
from transform_excel_tools.util import path_utils, file_utils, LogUtils

logger = LogUtils.get_logger("TransformData")
app_path = path_utils.app_path()

app = Flask(__name__, static_folder=app_path + '/statics',
            template_folder=app_path + '/templates')

INPUT_FILE_DIR = app_path + '/需求文件'
OUTPUT_FILE_DIR = app_path + '/结果文件'

# 变电运检专业
SUBSTATION_INFO = [{'subject_type': "substation", 'name': "变电运检专业"}]
SUBSTATION_FORM_LIST = [{'name': "1", 'dir_path': '{}/{}/1'.format(INPUT_FILE_DIR, SUBSTATION_INFO[0].get('name'))},
                        {'name': "2", 'dir_path': '{}/{}/2'.format(INPUT_FILE_DIR, SUBSTATION_INFO[0].get('name'))},
                        {'name': "3", 'dir_path': '{}/{}/3'.format(INPUT_FILE_DIR, SUBSTATION_INFO[0].get('name'))}]


# 线路运检专业


# web
@app.route('/')
@app.route('/index')
@app.route('/index/')
def index_web():
    return render_template('index.html')


@app.route('/substation')
def substation_web():
    return render_template('substation.html')


@app.route('/select-file/<subject_type>')
def select_file_web(subject_type):
    info = None
    form_list = None
    if subject_type == 'substation':
        info = SUBSTATION_INFO
        form_list = SUBSTATION_FORM_LIST
    return render_template('select-file.html', info=info, form_list=form_list)


@app.route('/finish/<subject_type>', methods=['POST'])
def finish_web(subject_type):
    file_list = []
    info = None
    if subject_type == 'substation':
        for item in SUBSTATION_FORM_LIST:
            file_list.append({'name': item['name'], 'path': request.form[item['name']]})
        info = SUBSTATION_INFO
    return render_template('finish.html', info=info, file_list=file_list)


# service
@app.route('/check-file')
def file_check_service():
    file_list = file_utils.get_dir_file_path(request.args.get("path"), ['.xls', '.xlsx'])
    file_modified_time_list = sorted(file_utils.get_file_modified_time(file_list), key=lambda d: d['modified_time'],
                                     reverse=True)
    data = list(map(lambda x: {"path": x['path'], 'modified_time': str(x['modified_time'])}, file_modified_time_list))
    response = JsonResponse(True, data)
    return response.to_json()


@app.route('/open-dir')
def open_dir_service():
    path = request.args.get("path")
    file_utils.start_file(path)
    response = JsonResponse(True, None)
    return response.to_json()


@app.route('/transform/<subject_type>')
def transform_service(subject_type):
    file_list_args = request.args.get("file_list").replace("'", '"')
    file_list = json.loads(file_list_args)
    success = False
    data = None
    if subject_type == 'substation':
        success, data = TransformData.transform_substation_data(file_list, "{}/{}".format(OUTPUT_FILE_DIR,
                                                                                          SUBSTATION_INFO[0].get(
                                                                                              'name')))
    response = JsonResponse(success, data)
    return response.to_json()

